package cn.uncode.rpc.util;

import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import cn.uncode.rpc.common.CommonConstant;
import cn.uncode.rpc.common.log.Logger;
import cn.uncode.rpc.common.log.LoggerFactory;
import cn.uncode.rpc.core.Exporter;
import cn.uncode.rpc.core.URL;
import cn.uncode.rpc.core.URLParam;
import cn.uncode.rpc.exception.ConfigException;
import cn.uncode.rpc.registry.Registry;
import cn.uncode.rpc.registry.RegistryFactory;
import cn.uncode.rpc.spi.ExtensionLoader;






/**
 * 
 * Config tools
 *
 * @author fishermen
 * @version V1.0 created at: 2013-5-27
 */

public class ConfigUtil {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(ConfigUtil.class);

    /**
     * export fomart: protocol1:port1,protocol2:port2
     * 
     * @param export
     * @return
     */
    public static Map<String, Integer> parseExport(String export) {
        if (StringUtils.isBlank(export)) {
            return Collections.emptyMap();
        }
        Map<String, Integer> pps = new HashMap<String, Integer>();
        String[] protocolAndPorts = CommonConstant.COMMA_SPLIT_PATTERN.split(export);
        for (String pp : protocolAndPorts) {
            if (StringUtils.isBlank(pp)) {
                continue;
            }
            String[] ppDetail = pp.split(":");
            if (ppDetail.length == 2) {
                pps.put(ppDetail[0], Integer.parseInt(ppDetail[1]));
            } else if (ppDetail.length == 1) {
                if (CommonConstant.PROTOCOL_INJVM.equals(ppDetail[0])) {
                    pps.put(ppDetail[0], CommonConstant.DEFAULT_INT_VALUE);
                } else {
                    int port = MathUtil.parseInt(ppDetail[0], 0);
                    if (port <= 0) {
                        throw new ConfigException("Export is malformed :" + export);
                    } else {
                        pps.put(CommonConstant.PROTOCOL_UNCODE, port);
                    }
                }

            } else {
                throw new ConfigException("Export is malformed :" + export);
            }
        }
        return pps;
    }

    public static String extractProtocols(String export) {
        Map<String, Integer> protocols = parseExport(export);
        StringBuilder sb = new StringBuilder(16);
        for (String p : protocols.keySet()) {
            sb.append(p).append(CommonConstant.COMMA_SEPARATOR);
        }
        if (sb.length() > 0) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();

    }
    
    
    public static <T> void unexport(List<Exporter<T>> exporters, Collection<URL> registryUrls) {
		try {
			unRegister(registryUrls);
		} catch (Exception e1) {
			LOGGER.warn("Exception when unregister urls:" + registryUrls);
		}
		try {
			for (Exporter<T> exporter : exporters) {
				exporter.unexport();
			}
		} catch (Exception e) {
			LOGGER.warn("Exception when unexport exporters:" + exporters);
		}
	}

	private static void unRegister(Collection<URL> registryUrls) {
		for (URL url : registryUrls) {
			// 不管check的设置如何，做完所有unregistry，做好清理工作
			try {
				String serviceStr = StringTools.urlDecode(url.getParameter(URLParam.EMBED.getName()));
				URL serviceUrl = URL.valueOf(serviceStr);

				RegistryFactory registryFactory = ExtensionLoader.getExtensionLoader(RegistryFactory.class)
						.getExtension(url.getProtocol());
				Registry registry = registryFactory.getRegistry(url);
				registry.unregister(serviceUrl);
			} catch (Exception e) {
				LOGGER.warn(String.format("unregister url false:%s", url), e);
			}
		}
	}
}
